<template>
  <div>
    <UploadExcel :on-success="onSuccess" />
  </div>
</template>

<script>
import { ImportEmployeesApi } from '@/api'
export default {
  name: 'VueAdminTemplateMasterIndex',

  data() {
    return {

    }
  },

  mounted() {

  },

  methods: {
    // 通过 props传入函数，返回一个excel数据的对象   header key  results value
    async onSuccess({ header, results }) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      // 遍历数组将 key替换为英文
      const excelObj = results.map(item => {
        const obj = {}
        Object.keys(item).forEach(key => {
          // 处理导入的时间 判断是否为时间
          if (userRelations[key] === 'timeOfEntry' || userRelations[key] === 'correctionTime') {
            // 后端限制了 不能是字符串 要转换为时间
            obj[userRelations[key]] = new Date(this.formatExcelDate(item[key]))
          } else {
            obj[userRelations[key]] = item[key]
          }
        })
        return obj
      })
      await ImportEmployeesApi(excelObj)
      this.$message.success('导入员工信息成功！')
      // 返回上一级页面
      this.$router.back()
    },

    // 格式化导入excel文件的时间
    formatExcelDate(numb, format = '/') {
      const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
      time.setYear(time.getFullYear())
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
